package com.jiyun.wait.service.impl;

import cn.hutool.core.date.DateUtil;
import com.jiyun.pojo.driver.Driver;
import com.jiyun.pojo.order.OrderCost;
import com.jiyun.pojo.order.OrderInformation;
import com.jiyun.pojo.order.OrderTime;
import com.jiyun.result.Result;

import com.jiyun.wait.mapper.WaitMapper;
import com.jiyun.wait.service.WaitService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.Random;
import java.util.UUID;

@Slf4j
@Service
public class WaitServiceImpl implements WaitService , ApplicationEventPublisherAware {

    @Autowired
    private WaitMapper waitMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    //创建事件发布者
    private ApplicationEventPublisher applicationEventPublisher;
    // 获取排队人数
    @Override
    public int waitPeople() {
        // 查询当前队列的消费者数量
        try {
            return rabbitTemplate.execute(channel -> {
                var info = channel.queueDeclarePassive("orderProcessing");
                return info.getMessageCount();
            });
        } catch (Exception e) {
            log.error("查询队列消费者数量时发生错误", e);
            return -1; // 返回一个特殊值表示查询失败
        }
    }
    //取消订单(有司机接单)
    @Transactional
    @Override
    public Result closeOrder(OrderInformation orderInformation) {
        try {
            int result = waitMapper.closeOrder(orderInformation);
            if (result > 0) {
                OrderTime orderTime = new OrderTime();
                orderTime.setOrderId(orderInformation.getOrderId());
                orderTime.setCancelTime(new Date());
                waitMapper.updateCancelTime(orderTime);

                rabbitTemplate.convertAndSend("passengerCancelsOrder", orderInformation.getOrderId());

                return Result.ok();
            } else {
                return Result.error("关闭订单失败");
            }
        } catch (Exception e) {
            log.error("关闭订单时发生错误", e);
            return Result.error("关闭订单失败");
        }
    }

    //查询司机
    @Override
    public Result findSelectDriver() {
        try {
            String driverId = (String) redisTemplate.opsForValue().get("DriverTakesOrders");
            if (driverId!= null) {
                return Result.ok(waitMapper.findSelectDriver(Integer.parseInt(driverId)));
            } else {
                return Result.error("未找到接单司机信息");
            }
        } catch (Exception e) {
            log.error("查找接单司机信息时发生错误", e);
            return Result.error("查找接单司机信息失败");
        }
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    //发布事件方法
    public void publishEvent(OrderInformation event) {
        // 直接发送到队列
        rabbitTemplate.convertAndSend("orderProcessing", event);
    }
    //取消订单（无司机接单）
    @Override
    public Result closeOrderNoPeople(OrderInformation orderInformation) {
        try {
            Message message = rabbitTemplate.receive("orderProcessing");
            log.info("消费消息:{}", message);
            int result = waitMapper.closeOrderNoPeople(orderInformation);
            if (result > 0) {
                return Result.ok();
            } else {
                return Result.error("关闭无人接单订单失败");
            }
        } catch (Exception e) {
            log.error("关闭无人接单订单时发生错误", e);
            return Result.error("关闭无人接单订单失败");
        }
    }
    //通过订单id查询订单
    @Override
    public Result selectOrderByOrderId(OrderInformation orderInformation) {
        try {
            OrderInformation orderInfo = waitMapper.selectOrderByOrderId(orderInformation);
            if (orderInfo!= null) {
                return Result.ok(orderInfo);
            } else {
                return Result.error("未找到对应订单");
            }
        } catch (Exception e) {
            log.error("查询订单信息失败", e);
            return Result.error("查询订单信息失败");
        }
    }

    @Transactional
    //保存订单的等待时间
    @Override
    public Result saveOrderTime(OrderInformation orderInformation) {
        try {
            if ("0".equals(orderInformation.getWaitOrderTime())) {
                orderInformation.setWaitOrderTime("1");
            }
            int result = waitMapper.saveOrderTime(orderInformation);
            if (result > 0) {
                return Result.ok();
            } else {
                return Result.error("保存订单等待时间失败");
            }
        } catch (Exception e) {
            log.error("保存订单等待时间时发生错误", e);
            return Result.error("保存订单等待时间失败");
        }
    }

    //轮询查询订单状态
    @Override
    public Result selectOrderStatus(OrderInformation orderInformation) {
        try {
            OrderInformation orderInfo = waitMapper.selectOrderByOrderId(orderInformation);
            if (null != orderInfo) {
                int orderStatus = orderInfo.getOrderStatus();
                if (orderStatus == 4) {
                    return Result.error("订单被司机取消");
                } else if (orderStatus == 2) {
                    return Result.ok(1);
                } else {
                    return Result.ok();
                }
            } else {
                return Result.error("未找到订单");
            }
        } catch (Exception e) {
            log.error("查询订单状态失败", e);
            return Result.error("查询订单状态失败");
        }
    }
    //重新发单
    @Override
    @Transactional
    public Result saveOrder(OrderInformation orderInformation) {
        try {
            // 查找原始订单信息
            OrderInformation originalOrder = waitMapper.selectOrderByOrderId(orderInformation);
            OrderCost orderCost = waitMapper.selectOrderCostByOrderId(orderInformation);
            OrderTime orderTime = waitMapper.selectOrderTimeByOrderId(orderInformation);

            // 生成新的订单 ID
            String newOrderId = String.valueOf(UUID.randomUUID());
            originalOrder.setOrderId(newOrderId);
            originalOrder.setOrderStatus(0);
            orderTime.setOrderTime(new Date());
            originalOrder.setDriverId(null);


            // 保存新订单信息到数据库
            waitMapper.saveOrder(originalOrder);
            waitMapper.saveOrderCost(orderCost);
            waitMapper.saveOrderTimeOnOrderTime(orderTime);

            OrderInformation orderInformation2 = new OrderInformation();
            orderInformation2.setOrderId(newOrderId);
            OrderInformation orderInformation1 = waitMapper.selectOrderByOrderId(orderInformation2);
            // 将订单发送到队列中
            rabbitTemplate.convertAndSend("orderProcessing", orderInformation1.getId());

            return Result.ok(newOrderId);
        } catch (Exception e) {
            log.error("保存订单失败", e);
            throw new RuntimeException("保存订单失败");
        }
    }
    //司机到达乘客起点
    public int queueListener(){
        try {
            Object messageObj = redisTemplate.opsForValue().get("ReachTheDestination");
            if (messageObj!= null) {
                return 1;
            } else {
                return 0;
            }
        } catch (Exception e) {
            log.error("查询 Redis 时出现错误", e);
            return 0;
        }
    }
    //查询司机信息
    @Override
    public Result selectDriverById(Driver driver) {
        try {
            Driver driverInfo = waitMapper.selectDriverById(driver);
            if (driverInfo!= null) {
                return Result.ok(driverInfo);
            } else {
                return Result.error("未找到对应司机");
            }
        } catch (Exception e) {
            log.error("查询司机信息失败", e);
            return Result.error("查询司机信息失败");
        }
    }
    //查询司机是否到达
    @Override
    public int selectOrderStatusIsArrive(OrderInformation orderInformation) {
        try {
            OrderInformation orderInfo = waitMapper.selectOrderByOrderId(orderInformation);
            if (orderInfo!= null) {
                int orderStatus = orderInfo.getOrderStatus();
                if (orderStatus == 6) {
                    return 1;
                } else {
                    return 0;
                }
            } else {
                return 0;
            }
        } catch (Exception e) {
            log.error("查询订单状态时出现错误", e);
            return 0;
        }
    }
    //查询订单是否被司机接单
    public int selectOrderStatusIsTake(String orderId){
        String driverId = (String) redisTemplate.opsForValue().get("DriverTakesOrders");
        OrderInformation orderInformation=waitMapper.selectOrderStatusIsTake(orderId);
        if (!ObjectUtils.isEmpty(orderInformation)){
            if (orderInformation.getOrderStatus()==1){
                if (driverId!=null){
                    return 0;
                }else {
                    return 1;
                }
            }else {
                return 1;
            }
        }else {
            return 1;
        }
    }
}
